package cn.itcast.security;

import cn.itcast.interfaces.UserService;
import cn.itcast.pojo.Permission;
import cn.itcast.pojo.Role;
import cn.itcast.pojo.User;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author: peterChen
 * @date: 2019/8/16 15:53
 * @description: TODO
 * @version: 1.0
 */

@Component
public class SpringSecurityUserService implements UserDetailsService {
    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //调用远程服务，获取用户的信息
        User user = userService.findByUsername(username);
        if(user == null){
            //用户不存在
            return null;
        }
        //创建权限列表
        List<GrantedAuthority> list = new ArrayList<>();
        //获取user中的角色信息
        Set<Role> roles = user.getRoles();
        //遍历，获取roles中premission的权限信息
        for (Role role : roles) {
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        //根据username、password、权限列表list获取userDetails对象
        UserDetails userDetails = new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
        return userDetails;
    }
}
